package com.xinchuang.config;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.merge.AbstractMergeStrategy;
import com.alibaba.fastjson.JSON;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.*;
import java.util.stream.IntStream;

/**
 * @Description:自定义单元格合并策略
 * @Author: thh
 * @Date: 2023/10/13 15:28
 */
@Data
@Slf4j
public class MyMergeStrategy extends AbstractMergeStrategy {

    private Sheet sheet;
    private Map<String, List<Integer>> templateMap;
    private Map<String, Object> dataMap;
    private boolean flag = true;
    private List<CellRangeAddress> addCellRangeAddressList;


    public MyMergeStrategy(Map<String, List<Integer>> templateMap, Map<String, Object> dataMap) {
        this.templateMap = templateMap;
        this.dataMap = dataMap;
    }

    @Override
    protected void merge(Sheet sheet, Cell cell, Head head, Integer integer) {
        this.sheet = sheet;
        this.addCellRangeAddressList = new ArrayList<>();
        if (flag) {
            //需要增加的行
            int addRow = 0;
            List<CellRangeAddress> mergedRegionsList = sheet.getMergedRegions();
            System.out.println(JSON.toJSONString(mergedRegionsList));
            //变量前缀
            String varPreStr = StringUtils.substringBefore(StringUtils.substringAfter(templateMap.keySet().stream().findFirst().orElse(""), "{"), ".");
            for (Map.Entry<String, List<Integer>> entry : templateMap.entrySet()) {
                String type = StringUtils.substringBefore(StringUtils.substringAfter(entry.getKey(), "{"), ".");
                List<?> list = (List<?>) dataMap.get(type);
                if (Objects.nonNull(list) && !list.isEmpty()) {
                    if (!varPreStr.equals(type)) {
                        addRow = addRow + list.size();
                    } else {
                        addRow = list.size();
                    }
                    mergeCellRangeAddress(entry, addRow, mergedRegionsList);
                }
            }
            addCellRangeAddressList.forEach(x -> {
                sheet.addMergedRegion(x);
            });
            flag = false;
        }
    }

    private void mergeCellRangeAddress(Map.Entry<String, List<Integer>> entry, int addRow, List<CellRangeAddress> mergedRegionsList) {
        List<Integer> value = entry.getValue();
        int rowStartIndex = value.get(0);
        int rowEndIndex = value.get(1);
        int columnStartIndex = value.get(2);
        int columnEndIndex = value.get(3);
        List<Integer> cellRangeAddRessIndexList = new ArrayList<>();
        for (int i = 0; i < addRow; i++) {
            CellRangeAddress cellRangeAddressNew = new CellRangeAddress(rowStartIndex + i, rowEndIndex + i, columnStartIndex, columnEndIndex);
            //当前sheet页包含的合并单元格 有交集就删除之前区域
//            Arrays.stream(IntStream.range(0, mergedRegionsList.size())
//                    .filter(e -> compareColAndRow(mergedRegionsList.get(e), cellRangeAddress))
//                    .toArray()).forEach(index -> {
//                System.out.println(index);
//                sheet.removeMergedRegion(index);
//            });
            for (int j = sheet.getNumMergedRegions() - 1; j >= 0; j--) {
                CellRangeAddress cellRangeAddressPre = sheet.getMergedRegion(j);
                boolean b = cellRangeAddressPre.intersects(cellRangeAddressNew);
                if (b) {
                    cellRangeAddRessIndexList.add(j);
                    // sheet.removeMergedRegion(j);
                    log.debug("===========");
                    log.debug("旧坐标:{},{},{},{}", cellRangeAddressPre.getFirstColumn(), cellRangeAddressPre.getLastColumn(), cellRangeAddressPre.getFirstRow(), cellRangeAddressPre.getLastRow());
                    log.debug("新坐标:{},{},{},{}", cellRangeAddressNew.getFirstColumn(), cellRangeAddressNew.getLastColumn(), cellRangeAddressNew.getFirstRow(), cellRangeAddressNew.getLastRow());
                    break;
                }
            }
            addCellRangeAddressList.add(cellRangeAddressNew);
            //  sheet.addMergedRegion(cellRangeAddressNew);
        }
        sheet.removeMergedRegions(cellRangeAddRessIndexList);
    }

    private static boolean compareColAndRow(CellRangeAddress cellRangeAddressPre, CellRangeAddress cellRangeAddressNew) {
        //log.debug("===========");
        //log.debug("旧坐标:{},{},{},{}", cellRangeAddressPre.getFirstColumn(), cellRangeAddressPre.getLastColumn(), cellRangeAddressPre.getFirstRow(), cellRangeAddressPre.getLastRow());
        // log.debug("新坐标:{},{},{},{}", cellRangeAddressNew.getFirstColumn(), cellRangeAddressNew.getLastColumn(), cellRangeAddressNew.getFirstRow(), cellRangeAddressNew.getLastRow());
        return (cellRangeAddressNew.getFirstColumn() <= cellRangeAddressPre.getFirstColumn()) &&
                (cellRangeAddressNew.getLastColumn() >= cellRangeAddressPre.getLastColumn()) &&
                (cellRangeAddressNew.getFirstRow() <= cellRangeAddressPre.getFirstRow()) && cellRangeAddressNew.getLastRow() >= cellRangeAddressPre.getLastRow();
    }


}
